//
//  NavigationController.m
//  LotteryClient
//
//  Created by Suny on 14-7-7.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "UIViewController+Custom.h"
#import "WeakObject.h"
#import "NavigationController.h"
#import "BaseViewController.h"
#import "TabViewController.h"

#define             kTransformStartValue 0.9
#define               kTransformEndValue 1.0

@interface NavigationController ()<UIGestureRecognizerDelegate>
{
    NSMutableSet * _simultaneousGestures;
}

@property (nonatomic,strong) BaseViewController *currentOperationController;
@end

@implementation NavigationController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//	self.view.backgroundColor = [UIColor colorWithRed:145/255.0
//												green:211/255.0
//												 blue:95/255.0
//												alpha:1.0];
	
	[self.navigationBar setTranslucent:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (id)init
{
    self = [super init];
    if (self)
    {
        [self initCustomVars];
    }

    return self;
}

- (void)dealloc
{

}

- (id)initWithNavigationBarClass:(Class)navigationBarClass toolbarClass:(Class)toolbarClass
{
    self = [super initWithNavigationBarClass:navigationBarClass toolbarClass:toolbarClass];
    if (self)
    {
        [self initCustomVars];
    }
    return self;
}

- (id)initWithRootViewController:(UIViewController *)rootViewController
{
    self = [super initWithNavigationBarClass:[NavigationBar class] toolbarClass:nil];
    if (self)
    {
        [self initCustomVars];
        [self pushViewController:rootViewController animated:NO];

    }
    return self;
}

- (void)initCustomVars
{

    self.navigationBarHidden = YES;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(pan:)];
    pan.maximumNumberOfTouches = 1;
    pan.minimumNumberOfTouches = 1;
    pan.delaysTouchesEnded = NO;
    pan.delegate = self;
    [self.view addGestureRecognizer:pan];


    _simultaneousGestures = [[NSMutableSet alloc] init];


}

- (void)setNavigationBarHidden:(BOOL)navigationBarHidden
{
	[super setNavigationBarHidden:navigationBarHidden];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
//    [self setNavigationControllerOfViewController:viewController
//                                       navigation:self];

    [super pushViewController:viewController animated:animated];

}

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
{
	TabViewController *tabViewController = [self.viewControllers objectAtIndex:0];
	if ([tabViewController isKindOfClass:[TabViewController class]])
	{
		tabViewController.selectedIndex = 0;
	}
    NSArray *array = [super popToRootViewControllerAnimated:animated];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [self setNavigationControllerOfViewController:obj navigation:nil];
    }];

    return  array;
}

- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    NSArray *array = [super popToViewController:viewController animated:animated];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [self setNavigationControllerOfViewController:obj navigation:nil];
    }];

    return  array;
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    UIViewController *controller = [super popViewControllerAnimated:animated];
    [self setNavigationControllerOfViewController:controller
                                       navigation:nil];
    return controller;
}

- (void)setNavigationControllerOfViewController:(UIViewController *)viewController
                                     navigation:(NavigationController *)navigation
{
    if ([viewController isKindOfClass:[BaseViewController class]])
    {
        if ([viewController respondsToSelector:@selector(customNavigationController)])
        {
            [(BaseViewController *)viewController setCustomNavigationController:navigation];
			[(BaseViewController *)viewController setHasNavigationBar:YES];

        }

    }
}



- (CGPoint)adjustedTranslation:(CGPoint)translation
{
    CGPoint adjustedTranslation = translation;
    CGRect frame = CGRectOffset(self.currentOperationController.view.frame, translation.x, 0);
    if (translation.x < 0 &&
            CGRectGetMinX(frame) < CGRectGetMinX(self.view.bounds))
    {
        adjustedTranslation.x = CGRectGetMinX(self.view.bounds) - CGRectGetMinX(self.currentOperationController.view.frame);
    }
    else if (translation.x > 0
            && CGRectGetMinX(frame) > CGRectGetMaxX(self.view.bounds))
    {
        adjustedTranslation.x = CGRectGetMaxX(self.view.bounds) - CGRectGetMinX(self.currentOperationController.view.frame);
    }

    return adjustedTranslation;
}



- (void)pan:(UIPanGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        // cancel gesture
        for (WeakObject * weakObject in _simultaneousGestures)
        {
            UIGestureRecognizer *gestureRecognizer = weakObject.object;
            if (gestureRecognizer)
            {
                gestureRecognizer.enabled = NO;
                gestureRecognizer.enabled = YES;
            }

        }

        [_simultaneousGestures removeAllObjects];

        CGPoint translation = [gesture translationInView:self.view];

        if (translation.x >= 0)
        {
            UIViewController *viewController = [self popViewControllerAnimated:NO];
            if ([viewController isKindOfClass:[BaseViewController class]] )
            {
                self.currentOperationController = (BaseViewController *)viewController;
            }
            CGRect frame = self.currentOperationController.view.frame ;
            frame.origin.x = 0;
            frame.origin.y = (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(IOS_7_0)) ? 0 : kDefaultStatusBarHeight;
            self.currentOperationController.view.frame = frame;
            [self.view addSubview:self.currentOperationController.view];
        }

    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {

        CGPoint translation = [self adjustedTranslation:[gesture translationInView:self.view]];
        self.currentOperationController.view.frame = CGRectOffset(self.currentOperationController.view.frame, translation.x, 0);
        [gesture setTranslation:CGPointZero inView:self.view];

        //亮度变换
        self.topViewController.maskView.alpha = 1 - self.currentOperationController.view.frame.origin.x / self.currentOperationController.view.frame.size.width;

//        //大小变换
//        CGFloat factor = self.currentOperationController.view.frame.origin.x/CGRectGetWidth(self.currentOperationController.view.bounds);
//        CGFloat scale = 1.0;
//        scale = (CGFloat) (kTransformStartValue+factor*(kTransformEndValue - kTransformStartValue));
//        self.topViewController.view.transform = CGAffineTransformMakeScale(scale, scale);
    }
    else if (gesture.state == UIGestureRecognizerStateEnded ||
            UIGestureRecognizerStateCancelled == gesture.state)
    {
        float dx = 0;

        if (fabs(self.currentOperationController.view.frame.origin.x)/([UIScreen mainScreen].applicationFrame.size.width) > 0.5 &&
                gesture.state ==  UIGestureRecognizerStateEnded)
        {
            dx = [UIScreen mainScreen].applicationFrame.size.width +10;
        }
        CGRect frame = self.currentOperationController.view.frame ;
        frame.origin.x = dx;

        [UIView animateWithDuration:0.5
                         animations:^{
            self.currentOperationController.view.frame = frame;

            if (dx == 0)
            {

                self.topViewController.maskView.alpha = 0.7;
//                self.topViewController.view.transform = CGAffineTransformMakeScale(kTransformStartValue, kTransformStartValue);

            }
            else
            {
                self.topViewController.maskView.alpha = 0;
//                self.topViewController.view.transform = CGAffineTransformMakeScale(kTransformEndValue, kTransformEndValue);
            }
        } completion:^(BOOL finished) {

            if (self.currentOperationController)
            {
                [self.currentOperationController.view removeFromSuperview];
//                self.topViewController.view.transform = CGAffineTransformMakeScale(kTransformEndValue, kTransformEndValue);


                if (dx == 0)
                {
                    [self pushViewController:self.currentOperationController animated:NO];
                }

            }
            self.currentOperationController = nil;
        }];

    }

}

#pragma mark - Gesture Delegate

- (BOOL)shouldBeginPanGestureRecognizer
{
    BOOL shouldBegin = YES;

    UIViewController *controller = self.currentOperationController;
    if (controller == nil
            || controller.modalViewController
            || (controller.navigationController && [controller.navigationController viewControllers].count > 1)) {
        shouldBegin = NO;
    }

    return shouldBegin;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    // clear gestures first
    BOOL shouldBegin = NO;
    if (!self.currentOperationController)
    {
        if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
        {
            UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer *)gestureRecognizer;
            CGPoint translation = [panGesture translationInView:self.view];
            CGPoint velocity = [panGesture velocityInView:self.view];

            if (fabs(translation.x /MAX(fabs(translation.y), 0.00001)) >= 2 &&
                    fabs(velocity.x) > fabs(velocity.y))
            {
                if (translation.x > 0)
                {
                    if ([self.viewControllers count] >= 2)
                    {
                        UIViewController *topViewController = self.topViewController;
                        if ([topViewController respondsToSelector:@selector(navigationController:shouldNavigateInteractiveGestureRecognizerBegin:)])
                        {
                            shouldBegin = [(id <NavigationControllerDelegate>)topViewController navigationController:self shouldNavigateInteractiveGestureRecognizerBegin:gestureRecognizer];
                        }
                        else
                        {
                            shouldBegin = NO;
                        }

                    }
                }
                else
                {
                    shouldBegin = NO;
                }
            }

        }
    }
    else
    {
        shouldBegin = NO;
    }


    return shouldBegin;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    BOOL shouldReceive = YES;


    return shouldReceive;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    [_simultaneousGestures addObject:[[WeakObject alloc] initWithObject:otherGestureRecognizer]];

    return YES;
}

//- (void)setNavigationBarHidden:(BOOL)navigationBarHidden
//{
//	[super setNavigationBarHidden:YES];
//}


@end

